package com.xywy.tangandroid.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
public class HttpUtil {
    private static final String TAG = "HttpUtil: ";

    //    private static final String CHARSET = "utf-8";

    /**
     * ����http����
     * @param uri ����uri��ַ
     * @param param �������
     * @param httpMethod ���󷽷�
     * @return
     */
    public static String request(String uri, Map<String, String> param,
        String httpMethod) {
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);

            int timeoutSocket = 10000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            if (TextUtils.isEmpty(uri)) {
                Log.e(TAG, "��Ч��URL��ַ");

                return "";
            }

            if (TextUtils.isEmpty(httpMethod)) {
                Log.e(TAG, "��Ч��httpMethod");

                return "";
            } else if ("get".equalsIgnoreCase(httpMethod)) {
                if ((param != null) && !param.isEmpty()) {
                    for (String key : param.keySet()) {
                        if (uri.contains("?")) {
                            uri += ("&" + (key + "=" + param.get(key)));
                        } else {
                            uri += ("?" + key + "=" + param.get(key));
                        }
                    }
                }

                HttpClient client = new DefaultHttpClient(httpParameters);
                HttpGet request = new HttpGet();
                request.setURI(new URI(uri));

                HttpResponse response = client.execute(request);

                /*��״̬��Ϊ200 ok*/
                if (response.getStatusLine().getStatusCode() == 200) {
                    /*ȡ����Ӧ�ַ���*/
                    String strResult = EntityUtils.toString(response.getEntity());

                    return strResult;
                } else {
                    Log.e(TAG,
                        "Error Response: " +
                        response.getStatusLine().toString());
                }
            } else if ("post".equalsIgnoreCase(httpMethod)) {
//                HttpClient hc = new DefaultHttpClient(httpParameters);
//                HttpPost request = new HttpPost(uri);
//                List<NameValuePair> params = new ArrayList<NameValuePair>();
//
//                if ((param != null) && !param.isEmpty()) {
//                    for (String key : param.keySet()) {
//                        params.add(new BasicNameValuePair(key,
//                                param.get(key).toString()));
//                    }
//
//                    if ((params != null) && !params.isEmpty()) {
//                        request.setEntity(new UrlEncodedFormEntity(params,
//                                HTTP.UTF_8));
//                    }
//                }
//
//                HttpResponse response = hc.execute(request);
//                BufferedReader br = new BufferedReader(new InputStreamReader(
//                            response.getEntity().getContent()));
//                StringBuffer sb = new StringBuffer();
//                String line = "";
//
//                if ((line = br.readLine()) != null) {
//                    sb.append(line);
//                }
//
//                return sb.toString();
                
                URL url = new URL(uri);
        		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        		connection.setDoOutput(true);
        		connection.setDoInput(true);
        		connection.setRequestMethod("POST");
        		connection.setConnectTimeout(1000 * 30);
        		connection.setUseCaches(false);
        		connection.setInstanceFollowRedirects(false);
        		connection.setRequestProperty("Content-Type",
        				"application/x-www-form-urlencoded");
        		connection.connect();
        		DataOutputStream out = new DataOutputStream(
        				connection.getOutputStream());
        		// Ҫ���Ĳ���
        		String content = "";
        		Iterator<Entry<String, String>> iter = param.entrySet().iterator();
        		while (iter.hasNext()) {
        			Map.Entry<String, String> entry = iter.next();
        			String key = entry.getKey();
        			String value = entry.getValue();
        			content += "&" + URLEncoder.encode(key, "UTF-8") + "="
        					+ URLEncoder.encode(value, "UTF-8");
        		}
        		if (content.length() > 1) {
        			content = content.substring(1);
        		}

        		out.writeBytes(content);
        		out.flush();
        		out.close();
        		BufferedReader inStream = new BufferedReader(new UnicodeReader(
        				connection.getInputStream(), "UTF-8"));
        		String result = "";
        		String str = "";

        		while ((str = inStream.readLine()) != null) {
        			if (!result.equals(""))
        				result = result + "\r\n" + str;
        			else
        				result = result + str;
        		}
        		inStream.close();
        		connection.disconnect();
        		return result; 
                
            } else {
                Log.e(TAG, "��Ч��httpMethod");
            }
        } catch (ClientProtocolException e) {
            Log.e(TAG, "���������쳣��msg:" + e.getMessage());
        } catch (Exception ee) {
            ee.printStackTrace();
            Log.e(TAG, "http�����쳣��msg:" + ee.getMessage());
        }

        return "";
    }

    /**
     * ��ȡԶ�̵�ַ�ļ���С
     * @param remoleUrl
     * @return
     */
    public static long getRemoleFileSize(String remoleUrl) {
        long size = 0;
        URL url;

        try {
            url = new URL(remoleUrl);

            HttpURLConnection connect = (HttpURLConnection) url.openConnection();
            size = connect.getContentLength();
        } catch (Exception e) {
            Log.e(TAG, "��ȡԶ���ļ���С����msg:" + e.getMessage());
        }

        return size;
    }

    /**
         * ��������Ƿ����
         *
         * @return ������ã�����true���������򷵻�false
         */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm == null) {
            return false;
        }

        NetworkInfo[] info = cm.getAllNetworkInfo();

        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }

        // return true;
        return false;
    }

    /**
    * �жϵ�ǰ����ģʽ�Ƿ���WIFI
    * @param context
    * @return ��wifi����true
    */
    public static boolean isWIFIConnect(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // //��ȡϵͳ�����ӷ���
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo(); // //��ȡ������������

        if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true; // wifi����
        } else {
            return false;
        }
    }

    /**
     * ʹ��Http�����ļ������������ֻ�Ŀ¼��
     *
     * @param urlStr
     * @param path
     * @param fileName
     * @return -1:�ļ����س��� 0:�ļ����سɹ�
     */
    public static boolean downFile(String urlStr, String path, String fileName) {
        InputStream inputStream = null;
        long filesize = 0;
        long readfilesize = 0;

        try {
            if (!path.endsWith("/")) {
                path += "/";
            }

            if (FileUtil.FileIsExist(path + fileName)) {
                FileUtil.deleteFile(path + fileName);
            }

            HttpClient client = new DefaultHttpClient();
            // �����������ӳ�ʱ�Ͷ����ݳ�ʱ
            client.getParams()
                  .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
                  .setParameter(CoreConnectionPNames.SO_TIMEOUT, 600000);

            HttpGet httpget = new HttpGet(urlStr);
            HttpResponse response = client.execute(httpget);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != 200) {
                return false;
            }

            InputStream fileStream = response.getEntity().getContent();
            filesize = response.getEntity().getContentLength();
            readfilesize = 0;

            File file = new File(path);

            if (!file.exists()) {
                FileUtil.createFileDirs(path);
            }

            FileOutputStream output = new FileOutputStream(path + fileName);
            ;

            byte[] buffer = new byte[1024];
            int len = 0;

            while ((len = fileStream.read(buffer)) > 0) {
                output.write(buffer, 0, len);
                readfilesize += len; //�ۼ����ص��ļ���С
            }

            fileStream.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }

            if (readfilesize < filesize) {
                if (FileUtil.FileIsExist(path + fileName)) {
                    FileUtil.deleteFile(path + fileName);
                }
            }
        }

        return true;
    }
}
